package com.avengers.modules.spider.bean.enums;

import com.avengers.modules.auction.bean.enums.Suffix;
import com.avengers.core.kit.DomainKit;
import com.avengers.core.kit.StringKit;

import java.util.stream.Stream;

/**
 * @author yu.wang
 * @since 2019-08-01 19:01
 **/
public enum DomainWhoisType {
    /**
     * 国内
     */
    zh(1, Suffix.cn.value, Suffix.cnZh.value),
    /**
     * com net
     */
    comNet(2, Suffix.com.value, Suffix.net.value),
    /**
     * org
     */
    org(3, Suffix.org.value),
    /**
     * cc
     */
    cc(4, Suffix.cc.value),
    /**
     * tv
     */
    tv(6, Suffix.tv.value),
    /**
     * others
     */
    other(5);

    public final Integer value;
    private final String[] suffix;

    DomainWhoisType(Integer value, String... suffix) {
        this.value = value;
        this.suffix = suffix;
    }

    public static DomainWhoisType of(Integer value) {
        for (DomainWhoisType queryType : values()) {
            if (queryType.value.equals(value)) {
                return queryType;
            }
        }
        return null;
    }


    public static DomainWhoisType of(String domain) {
        if (StringKit.isBlank(domain)) {
            return null;
        }
        String suffix = DomainKit.getSuffix(domain);
        if (StringKit.isBlank(suffix)) {
            return null;
        }
        for (DomainWhoisType value : values()) {
            if (Stream.of(value.suffix).anyMatch(s -> {
                if (zh.equals(value)) {
                    return domain.toLowerCase().endsWith(s);
                } else {
                    return suffix.toLowerCase().equals(s);
                }
            })) {
                return value;
            }
        }
        if (DomainKit.isDomain(domain)) {
            return other;
        }
        return null;
    }
}
